package com.example.dao;

import com.example.entity.Student5;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.util.List;

import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Update.update;

/**
 * @author ：liukai
 * @date ：Created in 2021/9/8 5:03 下午
 * @description：
 * @modified By：
 * @version: $
 */
@Repository
public class Student5DaoImpl implements Student5Dao {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public int insert(Student5 student5) {
        Student5 insert = mongoTemplate.insert(student5);
        return insert != null ? 1 : 0;
    }

    @Override
    public int updateById(Student5 student5) {
//        UpdateResult upsert = mongoTemplate.update(Student5.class)
//                .matching(Query.query(where("_id").is(student5.getId())))
//                .apply(update("name", student5.getName()))
//                .upsert();
        mongoTemplate.updateMulti(new Query(where("_id").is(student5.getId())),
                new Update().set("name", student5.getName()), Student5.class);
        return 1;
    }

    @Override
    public int deleteById(String id) {
        DeleteResult deleteResult = mongoTemplate.remove(Query.query(where("_id").is(id)), "students5");
        return (int) deleteResult.getDeletedCount();
    }

    @Override
    public List<Student5> findAll() {
//        List<Student5> list = mongoTemplate.findAll(Student5.class);
        return mongoTemplate.query(Student5.class)
                .matching(Query.query(where("name")
                        .in("u1", "u2", "u3"))
                        .limit(3)
                        .skip(3)
                        .with(Sort.by("score").descending()))
                .all();
    }

    @Override
    public List<Student5> findAllByPage(int page, int size) {
        return mongoTemplate.find(new Query().limit(size).skip((page - 1) * size), Student5.class);
    }
}
